import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 18
 * Time: 11:42
 */
//力扣144.二叉树的前序遍历
public class Solution1 {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode cur = root;
            TreeNode top = null;
            while(cur != null || !stack.isEmpty()) {//这个循环条件很重要，是最后才加上的
                while(cur != null) {
                    stack.push(cur);
                    list.add(cur.val);
                    cur = cur.left;
                }
                top = stack.pop();
                cur = top.right;
            }
            return list;
        }
}
